from flask import Blueprint, request, jsonify, send_file
import os
import json
import base64
import tempfile
import shutil
import zipfile
import logging
from datetime import datetime

bp = Blueprint('export', __name__)

@bp.route('/images', methods=['POST'])
def export_images():
    """
    将选中的分镜图片导出到指定文件夹
    请求格式：
    - folderName: 导出目录名称
    - shots: 要导出的分镜数组，每个分镜包含id、originalText和image
    """
    # 初始化temp_dir为None，确保finally块可以安全访问
    temp_dir = None
    try:
        logging.info("接收到导出图片请求")
        data = request.json
        logging.info(f"请求数据: {data}")
        
        if not data or 'folderName' not in data or 'shots' not in data:
            logging.error("请求数据格式错误: 缺少folderName或shots字段")
            return jsonify({
                "success": False,
                "error": '请提供导出目录名称和分镜数据'
            }), 400
        
        folder_name = data['folderName']
        shots = data['shots']
        logging.info(f"导出目录: {folder_name}, 分镜数量: {len(shots)}")
        logging.debug(f"分镜数据: {shots}")
        
        if not shots:
            logging.error("没有要导出的分镜")
            return jsonify({
                "success": False,
                "error": '没有要导出的分镜'
            }), 400
        
        # 创建临时目录
        temp_dir = tempfile.mkdtemp()
        export_dir = os.path.join(temp_dir, folder_name)
        os.makedirs(export_dir, exist_ok=True)
        logging.info(f"创建临时导出目录: {export_dir}")
        
        # 保存分镜信息
        info_file = os.path.join(export_dir, 'storyboard_info.json')
        with open(info_file, 'w', encoding='utf-8') as f:
            json.dump({
                'exportTime': datetime.now().isoformat(),
                'shots': [{
                    'id': shot.get('id', i),
                    'text': shot.get('originalText', '')
                } for i, shot in enumerate(shots)]
            }, f, ensure_ascii=False, indent=2)
        
        # 保存图片
        for i, shot in enumerate(shots):
            try:
                logging.info(f"处理第{i+1}个分镜")
                if 'image' not in shot or not shot['image']:
                    logging.error(f"第{i+1}个分镜缺少图片数据")
                    return jsonify({
                        "success": False,
                        "error": f'第{i+1}个分镜缺少图片数据'
                    }), 400
                
                try:
                    # 处理可能包含的data URL前缀
                    image_str = shot['image']
                    logging.debug(f"第{i+1}个分镜图片数据长度: {len(image_str) if image_str else 0}")
                    if ',' in image_str:
                        logging.debug(f"第{i+1}个分镜图片数据包含data URL前缀，进行分割处理")
                        image_str = image_str.split(',', 1)[1]
                    image_data = base64.b64decode(image_str)
                    logging.debug(f"第{i+1}个分镜图片数据解码成功，大小: {len(image_data)} 字节")
                except Exception as e:
                    logging.error(f"第{i+1}个分镜的图片数据格式错误: {str(e)}")
                    return jsonify({
                        "success": False,
                        "error": f'第{i+1}个分镜的图片数据格式错误: {str(e)}'
                    }), 400
                
                image_path = os.path.join(export_dir, f'shot_{i+1}.png')
                with open(image_path, 'wb') as f:
                    f.write(image_data)
                logging.info(f"第{i+1}个分镜图片保存成功: {image_path}")
            except Exception as e:
                return jsonify({
                    "success": False,
                    "error": f'保存第{i+1}个分镜图片时出错: {str(e)}'
                }), 500
        
        # 创建ZIP文件
        zip_path = os.path.join(temp_dir, f'{folder_name}.zip')
        logging.info(f"创建ZIP文件: {zip_path}")
        with zipfile.ZipFile(zip_path, 'w') as zipf:
            for root, _, files in os.walk(export_dir):
                for file in files:
                    file_path = os.path.join(root, file)
                    arcname = os.path.relpath(file_path, temp_dir)
                    zipf.write(file_path, arcname)
                    logging.debug(f"添加文件到ZIP: {arcname}")
        logging.info(f"ZIP文件创建成功: {zip_path}")
        
        # 返回ZIP文件
        return send_file(
            zip_path,
            as_attachment=True,
            download_name=f"{folder_name}.zip",
            mimetype="application/zip"
        )
    
    except Exception as e:
        logging.error(f"导出失败: {str(e)}", exc_info=True)
        return jsonify({
            "success": False,
            "error": f'导出失败: {str(e)}'
        }), 500
    finally:
        # 清理临时目录
        if temp_dir is not None:
            shutil.rmtree(temp_dir, ignore_errors=True)